import React, { useEffect, useRef, forwardRef, useImperativeHandle } from "react";
import "./EarthPolar.css";
import { EarthPolarRenderer } from "./EarthPolarRenderer";
import { LocationPoint, LatLngRect, DetectionPointWithApiFields } from "../types/earth";

export interface EarthPolarRef {
  zoomIn: () => void;
  zoomOut: () => void;
  resetView: () => void;
}

interface EarthPolarProps {
  polarType: "north" | "south";
  tileUrlTemplate?: string; // 瓦片URL模板（已包含planet_id）
  maxZoom?: number; // 最大缩放级别
  locationPoints?: LocationPoint[];
  detectionPoints?: DetectionPointWithApiFields[];
  dataAreas?: LatLngRect[];
  patrolAreas?: LatLngRect[]; // 新增巡视区数据
  onCoordinateClick?: (coord: { lat: number; lng: number } | null) => void;
  onCoordinateHover?: (coord: { lat: number; lng: number } | null) => void;
  onLocationClick?: (location: LocationPoint | null) => void;
  onLocationHover?: (location: LocationPoint | null) => void;
  onDetectionPointClick?: (detectionPoint: DetectionPointWithApiFields | null) => void;
  onDetectionPointHover?: (detectionPoint: DetectionPointWithApiFields | null) => void;
  onRectClick?: (rect: LatLngRect | null) => void;
  onRectHover?: (rect: LatLngRect | null) => void;
  onPatrolAreaClick?: (patrolArea: LatLngRect | null) => void;
  onPatrolAreaHover?: (patrolArea: LatLngRect | null) => void;
  onSelectionChange?: (selectionRect: LatLngRect | null) => void;
  onSelectionEnd?: (selectionRect: LatLngRect | null, intersectingRects: LatLngRect[], intersectingDetectionPoints: DetectionPointWithApiFields[]) => void;
  externalSelection?: LatLngRect | null;
  simulatedMetaKey?: boolean;
}

const EarthPolarNew = forwardRef<EarthPolarRef, EarthPolarProps>(function EarthPolarNew(props, ref) {
  const {
    polarType,
    tileUrlTemplate,
    maxZoom = 5,
    locationPoints = [],
    detectionPoints = [],
    dataAreas = [],
    patrolAreas = [], // 新增巡视区数据
    onCoordinateClick,
    onCoordinateHover,
    onLocationClick,
    onLocationHover,
    onDetectionPointClick,
    onDetectionPointHover,
    onRectClick,
    onRectHover,
    onPatrolAreaClick,
    onPatrolAreaHover,
    onSelectionChange,
    onSelectionEnd,
    externalSelection,
    simulatedMetaKey = false
  } = props;
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const rendererRef = useRef<EarthPolarRenderer | null>(null);

  // 初始化渲染器
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const renderer = new EarthPolarRenderer(canvas, polarType, {
      tileUrlTemplate,
      maxZoom,
      onCoordinateClick,
      onCoordinateHover,
      onLocationClick,
      onLocationHover,
      onDetectionPointClick,
      onDetectionPointHover,
      onRectClick,
      onRectHover,
      onPatrolAreaClick,
      onPatrolAreaHover,
      onSelectionChange,
      onSelectionEnd
    });

    rendererRef.current = renderer;

    return () => {
      renderer.destroy();
    };
  }, [polarType]);

  // 更新数据
  useEffect(() => {
    if (rendererRef.current) {
      rendererRef.current.setData(locationPoints, detectionPoints, dataAreas, patrolAreas);
    }
  }, [locationPoints, detectionPoints, dataAreas, patrolAreas]);

  // 更新外部选区
  useEffect(() => {
    if (rendererRef.current) {
      rendererRef.current.setExternalSelection(externalSelection || null);
    }
  }, [externalSelection]);

  // 更新模拟Meta键状态
  useEffect(() => {
    if (rendererRef.current) {
      rendererRef.current.setSimulatedMetaKey(simulatedMetaKey);
    }
  }, [simulatedMetaKey]);

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    zoomIn: () => {
      if (rendererRef.current) {
        rendererRef.current.zoomIn();
      }
    },
    zoomOut: () => {
      if (rendererRef.current) {
        rendererRef.current.zoomOut();
      }
    },
    resetView: () => {
      if (rendererRef.current) {
        rendererRef.current.resetView();
      }
    }
  }));

  return (
    <div className="earth-polar-container">
      <canvas
        ref={canvasRef}
        className="earth-polar-canvas"
        style={{
          cursor: simulatedMetaKey ? "crosshair" : "grab",
        }}
      />
    </div>
  );
});

export default EarthPolarNew;
